package com.scisoft.scan.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.scisoft.scan.data.UpdateVersionInfo;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.ws.SysParameter;

public class UpdateManager {
    //上下文
    private Context mContext;
    //版本更新信息
    private UpdateVersionInfo mUpdateVersionInfo;
    /* 下载包安装路径 */
    private static final String savePath = "/sdcard/dy/";
    /* apk文件名 */
    private static final String saveFileName = savePath + "dy-scanApp.apk";
    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    //下载中
    private static final int DOWN_UPDATE = 1;
    //下载完成
    private static final int DOWN_OVER = 2;
    //进度的百分比
    private int progress;
    //下载线程
    private Thread downLoadThread;
    //取消标记
    private boolean interceptFlag = false;

    //构造函数
    public UpdateManager(Context context,UpdateVersionInfo updateVersionInfo) {
        this.mContext = context;
        this.mUpdateVersionInfo = updateVersionInfo;
    }

    //显示下载进度条
    public void showDownloadDialog(){
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(mContext);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View dialogView = inflater.inflate(R.layout.dialog_updatedownload, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);
        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        //版本号
        TextView tv_versionName = dialogView.findViewById(R.id.tv_versionName);
        tv_versionName.setText("（" + mUpdateVersionInfo.versionName + "）");
        //进度条
        mProgress = dialogView.findViewById(R.id.progress);
        //取消按钮
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadApk();
    }

    //通过Handler来进行异步更新UI进度条
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    //更新下载进度
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    //下载完毕进行安装
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    //后台下载apk的线程
    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(mUpdateVersionInfo.apkUrl);

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if(!file.exists()){
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do{
                    int numread = is.read(buf);
                    count += numread;
                    progress =(int)(((float)count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                //需要提示
            } catch(IOException e){
                e.printStackTrace();
                //需要提示
            }

        }
    };

   //下载apk
    private void downloadApk(){
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }
    //安装apk
    private void installApk() {
        try {
            File apkfile = new File(saveFileName);
            if (!apkfile.exists()) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri uri = FileProvider.getUriForFile(mContext, "com.scisoft.scan.dy.fileprovider", apkfile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }else{
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            }
            mContext.startActivity(intent);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
    //获取uri
    public Uri getUri(Context context,String url){

        //判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            try{
                File tempFile = new File(url);
                return FileProvider.getUriForFile(context, "com.scisoft.scan.tsp.fileprovider", tempFile);
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            return Uri.parse(url);
        }
        return null;
    }
}
